/*
 * ManagePadBatchIDFrame.java
 *
 * Created on Jan 7, 2012, 10:20:24 PM
 */
package gui;

import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;

import util.Activity;
import util.ActivityComment;
import util.Authentication;
import util.ErrorMessage;

import db.DatabaseManager;
import db.entity.Padbatch;
/**
 *
 * @author suzann
 */
public class ManagePadBatchIDFrame extends javax.swing.JFrame {

    /** Creates new form ManagePadBatchIDFrame */
    public ManagePadBatchIDFrame() {
        initComponents();
        listPadLotID();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jtxNewPadBatchID = new javax.swing.JTextField();
        jbtCreate = new javax.swing.JButton();
        jbtDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Pad Batch ID");

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Pad Batch ID:");

        jbtCreate.setText("Create");
        jbtCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCreateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxNewPadBatchID, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(jbtCreate))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtxNewPadBatchID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtCreate)
                .addContainerGap(132, Short.MAX_VALUE))
        );

        jbtDelete.setText("Delete");
        jbtDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1)
                    .addComponent(jbtDelete))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtDelete)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-423)/2, (screenSize.height-334)/2, 423, 334);
    }// </editor-fold>
    private void listPadLotID()
    {
    	jList1.removeAll(); 	
    	DatabaseManager db = new DatabaseManager();
    	List<Padbatch> pList = db.getPadBatchID();
    	Vector<String> sList = new Vector<String>();
    	for(Padbatch pItem : pList)
    	{    	 
    		sList.add(pItem.getPadBatchID());
    	}    	
    	jList1.setListData(sList);
    }
    private void jbtDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
        //validate user selection
        if(jList1.getSelectedIndex() == -1)
        {
        	ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Invalid Pad Batch ID", "Please select a Pad Batch ID.");
        	return ;
        }
        
        // Validate User
    	String username = null;
    	boolean valid = false;
        do
        {
            username = Authentication.authenticateUser();
            if(username.equals("Invalid"))
                JOptionPane.showMessageDialog(this, "Your username is invalid.\nPlease enter your username again.", "Authentication Failure", JOptionPane.WARNING_MESSAGE);
            else if (username.equals("Exit"))
	           return;
            else
                if (username != null)
                    valid = true;
        }while(!valid);
                
        // Confirm user selection
        Object selectedValues[] = jList1.getSelectedValues();
        int confirm = JOptionPane.showConfirmDialog(null, "Confirm to delete "+selectedValues.length+" selected Pad Batch ID?", "Confirm Delete",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);       
        if(confirm == JOptionPane.NO_OPTION)
        	return ;

	   	// Get Activity Comment
	   	String comment = ActivityComment.getComment();
	   	if(comment.equals("Exit"))
	   		return ;
   	
        // Remove user selected Pad Batch ID
        DatabaseManager db = new DatabaseManager();
        
        String padBatchIDArray[] = new String[selectedValues.length];
        for(int i=0; i<selectedValues.length; i++)
        {
        	padBatchIDArray[i] = selectedValues[i].toString();
        	
        	if(db.getCountActiveStationByPadLotID(selectedValues[i].toString())!=0)
        	{
        		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Pad Lot in use", "Pad Batch ID is activated in one or more Station.");
        		return ;
        	}
        }
        	
        db.deletePadBatchID(padBatchIDArray);
        
        String activityLog_action = "Remove Pad Batch ID: ";
        for(int i=0; i<selectedValues.length; i++)
        	activityLog_action += padBatchIDArray[i]+"; ";
        Activity.log(activityLog_action, username, comment);
        
        // Repaint Pad Lot ID List
        listPadLotID();
        
        // also update Pad Lot ID of other frames
        PolynomialInputFrame.updatePadBatchID();
        ActivateStationFrame.updatePadLotID();
        PolyResultFrame.updatePadBatchID();
    }                                         

    private void jbtCreateActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // Validate User
    	String username = null;
    	boolean valid = false;
        do
        {
            username = Authentication.authenticateUser();
            if(username.equals("Invalid"))
                JOptionPane.showMessageDialog(this, "Your username is invalid.\nPlease enter your username again.", "Authentication Failure", JOptionPane.WARNING_MESSAGE);
            else if (username.equals("Exit"))
	           return;
            else
                if (username != null)
                    valid = true;
        }while(!valid);
        
        // Validate user input
        String newPadBatchID = jtxNewPadBatchID.getText();
        if(newPadBatchID.equals("") || newPadBatchID==null)
        {
        	ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Invalid Pad Batch ID", "Please fill in Pad Batch ID.");
        	return ;
        }
        
        for(int i=0; i<jList1.getModel().getSize(); i++)
        {
        	String padBatchID = jList1.getModel().getElementAt(i).toString();
        	if(newPadBatchID.equals(padBatchID))
        	{
        		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Invalid Pad Batch ID", "This ID an existing Pad Batch ID.");
            	return ;
        	}
        }
        
        // add pad batch id to db
        DatabaseManager db = new DatabaseManager();
        db.addPadBatchID(newPadBatchID);
        Activity.log("Insert New Pad Batch '"+newPadBatchID+"'", username, "");
        
        // repaint Pad Lot ID List
        listPadLotID();
        
        // also update Pad Lot ID of other frames
        PolynomialInputFrame.updatePadBatchID();
        ActivateStationFrame.updatePadLotID();
        PolyResultFrame.updatePadBatchID();
    }                                         

    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManagePadBatchIDFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManagePadBatchIDFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManagePadBatchIDFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManagePadBatchIDFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ManagePadBatchIDFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtCreate;
    private javax.swing.JButton jbtDelete;
    private javax.swing.JTextField jtxNewPadBatchID;
    // End of variables declaration
}
